/**
 * STM32 RSA封装层
 * ProvideClass似于STM32硬件加密的接口
 */

#include "stm32f4xx_rsa.h"
#include "rsa_impl.h"
#include <string.h>

/* RSA上下文（全局） */
static RSA_Impl_Context rsa_ctx;
static uint8_t rsa_initialized = 0;
static uint8_t rsa_key_set = 0;

/**
 * @brief InitializeRSAModule
 */
HAL_StatusTypeDef RSA_Init(void)
{
    RSA_Impl_Init(&rsa_ctx);
    rsa_initialized = 1;
    rsa_key_set = 0;
    return HAL_OK;
}

/**
 * @brief SettingsRSAKey
 */
HAL_StatusTypeDef RSA_SetKey(uint8_t* key, uint32_t key_len)
{
    if (!rsa_initialized) {
        return HAL_ERROR;
    }
    
    if (key == NULL || key_len < 256) {  // Require256字节（N + D）
        return HAL_ERROR;
    }
    
    /* LoadKey */
    RSA_Impl_LoadKey(&rsa_ctx, key, key_len);
    rsa_key_set = 1;
    
    return HAL_OK;
}

/**
 * @brief ExecuteRSACommand（加密Or解密）
 */
HAL_StatusTypeDef RSA_ProcessCommand(uint8_t cmd, 
                                     const uint8_t* input, 
                                     uint32_t input_len,
                                     uint8_t* output, 
                                     uint32_t* output_len)
{
    if (!rsa_initialized || !rsa_key_set) {
        return HAL_ERROR;
    }
    
    if (input == NULL || output == NULL || output_len == NULL) {
        return HAL_ERROR;
    }
    
    /* CheckInput长度（必须Yes128字节） */
    if (input_len != RSA_IMPL_BLOCK_SIZE) {
        return HAL_ERROR;
    }
    
    *output_len = RSA_IMPL_BLOCK_SIZE;
    
    /* Execute操作 */
    if (cmd == RSA_CMD_ENCRYPT) {
        RSA_Impl_Encrypt(&rsa_ctx, input, output);
    } else if (cmd == RSA_CMD_DECRYPT) {
        RSA_Impl_Decrypt(&rsa_ctx, input, output);
    } else {
        return HAL_ERROR;
    }
    
    return HAL_OK;
}
